package com.api.qfengx.data.form;

import com.alibaba.fastjson.JSON;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.NumberUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.entity.Result;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author Qfengx <qffg1998@126.com>
 * @Date 2021-08-10 15:48:53
 */
@Path("/qfengx/data/form")
public class DataFormAPi {

    @GET
    @Path("/select/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String selectList(@Context HttpServletRequest request) {
        try {
            String tablename = request.getParameter("tablename");
            String fieldname = request.getParameter("fieldname");
            if (StringUtils.isEmpty(tablename) || StringUtils.isEmpty(fieldname)) {
                return JSON.toJSONString(Result.paramErr());
            }
            int dt = NumberUtils.parseInt(request.getParameter("dt"), 0);
            String dtname = "";
            String billid = DaoUtils.querySingleVal("select id from workflow_bill where tablename = ?", tablename);
            if (StringUtils.isEmpty(billid)) {
                return JSON.toJSONString(Result.fail("表单不存在"));
            }
            String fieldid = "";
            if (dt > 0) { // 明细表
                dtname = tablename + "_dt" + dt;
                fieldid = DaoUtils.querySingleVal("select id from workflow_billfield where billid = ? and detailtable = ? and fieldname = ?", billid, dtname, fieldname);
                if (StringUtils.isEmpty(fieldid)) {
                    return JSON.toJSONString(Result.fail("字段或明细表不存在"));
                }
            } else {
                fieldid = DaoUtils.querySingleVal("select id from workflow_billfield where billid = ? and (detailtable is null or detailtable = '') and fieldname = ?", billid, fieldname);
            }
            if (StringUtils.isEmpty(fieldid)) {
                return JSON.toJSONString(Result.fail("字段不存在"));
            }
            List<Map<String, String>> mapList = DaoUtils.executeQueryToMapList("select selectvalue, selectname, id from workflow_selectitem where fieldid = ? and cancel = 0", fieldid);
            return JSON.toJSONString(Result.ok(mapList));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }
}
